#include "stdafx.h"


Plane::Plane(const D3DXVECTOR3& position, const D3DXVECTOR3& size) :
	IDrawable(position, size, nullptr, nullptr)
{
	globals::d3dDevice->CreateVertexBuffer(4*sizeof(Vertex), D3DUSAGE_WRITEONLY, Vertex::FVF_Flags, D3DPOOL_DEFAULT, &mVertexBuffer, nullptr);
	float x = 1.f;
	Vertex vertices[4] = 
	{
		{ position.x,          position.y,          position.z,          0, 0 }, //, 0, 1, 0
		{ position.x + size.x, position.y,          position.z,          x, 0 },
		{ position.x,          position.y + size.y, position.z + size.z, 0, x },
		{ position.x + size.x, position.y + size.y, position.z + size.z, x, x }
	};

	void *pVertices;
	mVertexBuffer->Lock( 0, sizeof(vertices), (void**)&pVertices, 0 );

	memcpy( pVertices, vertices, sizeof(vertices) );
	mVertexBuffer->Unlock();
	
}


Plane::~Plane(void)
{
	if(mVertexBuffer != nullptr)
		mVertexBuffer->Release();

	if(mTexture != nullptr)
		mTexture->Release();
}


void Plane::render()
{
	globals::d3dDevice->SetRenderState( D3DRS_CULLMODE, D3DCULL_NONE);
	globals::d3dDevice->SetRenderState( D3DRS_ZWRITEENABLE, TRUE );
	globals::d3dDevice->SetTexture( 0, mTexture );

	globals::d3dDevice->SetStreamSource( 0, mVertexBuffer, 0, sizeof(Vertex) );
	globals::d3dDevice->SetFVF( Vertex::FVF_Flags );
	globals::d3dDevice->DrawPrimitive( D3DPT_TRIANGLESTRIP, 0, 2);

	globals::d3dDevice->SetRenderState( D3DRS_CULLMODE, D3DCULL_CW);
}


void Plane::setPosition(const D3DXVECTOR3& position)
{
	mPosition = position;
}

D3DXVECTOR3 Plane::getPosition()
{
	return mPosition;
}



void Plane::setTexture(const std::string& file)
{
	if(mTexture != nullptr)
		mTexture->Release();

	D3DXCreateTextureFromFile(globals::d3dDevice, file.c_str(), &mTexture);
}


std::string fakeGet()
{
	return nullptr;
}


void Plane::toLua()
{
	using luabind::def;
	using luabind::class_;

	luabind::module(lua::State())
	[
		class_<Plane>("Plane").
		def(luabind::constructor<const D3DXVECTOR3&, const D3DXVECTOR3&>()).
		def("render", &Plane::render).
		property("position", &Plane::getPosition, &Plane::setPosition).
		property("texture", &fakeGet, &Plane::setTexture)

	];
}